<?php

namespace App\Service\Activity\v1_3_0;

use App\Helpers\AliyunUtil;
use App\Helpers\ConfigUtil;
use App\Model\DailyTaskLog;
use App\Model\TaskProgressDay;
use App\Model\UserProfile;
use App\Service\BaseService;

/**
 * 签到信息
 */
class DailyTaskInfoService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $doneTaskIds = DailyTaskLog::checkToday($userId);
        $ret = [
            //每日任务
            'daily_task' => $this->packDailyTask($doneTaskIds, $userId),
            //新手任务
            'newly_task' => $this->packNewlyTask($doneTaskIds),
        ];
        //签到提示
        return $ret;
    }

    function packDailyTask($taskIds = [], $userId = 0)
    {
        $profile = UserProfile::getProfile($userId);
        $role = UserProfile::checkRoleHost($profile->role) ? 'host' : 'user';

        #获取进度条
        $taskRecord = collect(TaskProgressDay::getByUserID($userId));

        $list = array_values(ConfigUtil::getDailyTasks($role));
        foreach ($list as &$item) {
            $task_done = $taskRecord->where('task_id',$item['id'])->first();
            $task_total = (float)$task_done['task_total'];
            $item['task_done'] =  $task_total >= $item['task_total'] ? $item['task_total'] : $task_total;
            $item['name'] = $item['desc'];
        }

        $text = ['去完成', '可领取', '已领取'];
        $this->buildList($list, $taskIds, $text);
        return $list;
    }

    /**
     * 新手任务
     */
    function packNewlyTask($taskIds = [])
    {
        $list = array_values(ConfigUtil::getDailyTasks('newly'));
        $text = ['去认证', '可领取', '已领取'];
        $this->buildList($list, $taskIds, $text);
        return $list;
    }

    /**
     * 列表元素
     */
    function buildList(&$list = [], $taskIds = 0, $text = [])
    {
        foreach ($list as $k => &$item) {
            $status = !isset($taskIds[$item['id']]) ? DailyTaskLog::STATUS_UNDO : $taskIds[$item['id']];
            $item['buttong_text'] = $text[$status];
            //0-去完成, 1-可领取, 2-已领取
            $item['buttong_status'] = $status;
            //icon的角标值
            $item['icon'] = AliyunUtil::IMG_HOST_V2 . $item['icon'];
        }
        return;
    }
}
